package pers.yurwisher.rubick.common.user;

import cn.hutool.core.collection.ListUtil;
import lombok.Getter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import pers.yurwisher.rubick.common.enums.tip.SystemCustomTipEnum;
import pers.yurwisher.rubick.common.exception.SystemCustomException;

import java.util.Collection;
import java.util.List;

/**
 * @author yq
 * @date 2021/04/22 20:51
 * @description
 * @since V1.0.0 自定义用户
 */
@Getter
public class CustomUserDetails implements UserDetails {


    private static final long serialVersionUID = 6499159882230935571L;
    private final CurrentUser user;

    /**权限判断全部通过 ElPermissionService 完成*/
    private final List<GrantedAuthority> authorities;

    public CustomUserDetails(CurrentUser user) {
        this.authorities = ListUtil.empty();
        this.user = user;
    }

    /**
     * 当前用户
     *
     * @return CurrentUser
     */
    public static CurrentUser current() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new SystemCustomException(SystemCustomTipEnum.CREDENTIALS_INVALID);
        }
        Object principal = authentication.getPrincipal();
        if (principal == null) {
            throw new SystemCustomException(SystemCustomTipEnum.CREDENTIALS_INVALID);
        } else {
            //匿名用户
            if (principal instanceof String) {
                throw new SystemCustomException(SystemCustomTipEnum.CREDENTIALS_INVALID);
            }
            return ((CustomUserDetails) principal).user;
        }
    }

    /**
     * 当前用户ID
     *
     * @return 用户ID
     */
    public static Long id() {
        return current().getId();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getEnabled();
    }
}
